<?php
/*
 * @Author: zhx zhx.0830@qq.com
 * @Date: 2023-08-28 09:27:15
 * @LastEditors: zhx zhx.0830@qq.com
 * @LastEditTime: 2023-09-06 17:29:13
 * @FilePath: \cn-saas-new\app\Http\Requests\AdminuserRequest.php
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;

/**
 * 应用
 *
 * @Desc:验证请求类
 *
 * @author: zhx
 *
 * @Time: 2023/8/10 10:37
 */
class ApplicationRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * 获取应用于请求的验证规则。
     *
     * @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
     */
    public function rules(): array
    {
        $updateId = $this->route('application');
        if ($updateId) {
            $r = [
                'name' => [
                    'required',
                    'max:50',
                    Rule::unique('admin_application', 'name')->ignore($updateId),
                ],
                'logo' => 'required',
                'name' => 'required|unique:admin_application,name',
                'module' => 'required',
                'remark' => 'required',
                'status' => 'required',
            ];
        } else {
            $r = [
                'id' => '',
                'logo' => 'required',
                'name' => 'required|unique:admin_application,name',
                'module' => 'required',
                'remark' => 'required',
                'status' => 'required',
            ];
        }

        return $r;
    }

    public function messages(): array
    {
        $m = [
            'logo.required' => '请上传LOGO',
            'name.required' => '应用名称不能为空',
            'module.required' => '模块名称不能为空',
            'remark.required' => '说明不能为空',
            'status.required' => '状态不能为空',
        ];

        return $m;
    }

    public function all($keys = null)
    {
        $data = parent::all($keys);

        $data['home_address'] = $data['module'];
        $data['service_address'] = 'api/'.$data['module'];
        $data['number'] = md5((string) Str::uuid());

        return $data;
    }

    protected function failedValidation(Validator $validator)
    {
        $error = $validator->errors()->all();
        throw new HttpResponseException(response()->json(['msg' => $error[0], 'code' => '500', 'data' => 'error'], 500));
    }
}
